// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.warehouse.dbmanager.ui.action;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.dengues.commons.IDenguesSharedImage;
import org.dengues.commons.utils.ImageUtil;
import org.dengues.commons.utils.UIUtils;
import org.dengues.core.CorePlugin;
import org.dengues.warehouse.dbmanager.ui.AbstractEditorComposite;
import org.dengues.warehouse.dbmanager.ui.DatabaseManagerDialog;
import org.dengues.warehouse.dbmanager.ui.DatabaseManagerUtils;
import org.dengues.warehouse.i18n.Messages;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Display;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 1 2006-09-29 17:06:40Z qiang.zhang $
 * 
 */
public class RunSqlAction extends AbstractToolAction {

    private final AbstractEditorComposite sqlEditorComposite;

    private int id;

    /**
     * Qiang.Zhang.Adolf@gmail.com RunSqlAction constructor comment.
     * 
     * @param sqlEditorComposite
     */
    private RunSqlAction(AbstractEditorComposite sqlEditorComposite) {
        super(Messages.getString("RunSqlAction.RunSqlAction.Label")); //$NON-NLS-1$
        setImageDescriptor(ImageUtil.getDescriptor(IDenguesSharedImage.DBINFO_CONFIRM));
        this.sqlEditorComposite = sqlEditorComposite;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com RunSqlAction constructor comment.
     * 
     * @param abstractEditorComposite
     * @param id
     */
    public RunSqlAction(AbstractEditorComposite abstractEditorComposite, int id) {
        this(abstractEditorComposite);
        this.id = id;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.action.Action#run()
     */
    @Override
    public void run() {
        final String sql = sqlEditorComposite.getSqlText();
        IRunnableWithProgress progress = new IRunnableWithProgress() {

            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                monitor.beginTask("", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
                if (id == AbstractEditorComposite.SQL) {
                    try {
                        final Connection conn = CorePlugin.getDefault().getDesignerCoreService().getCurrentConnection();
                        Statement stmt = conn.createStatement();
                        stmt.execute(sql);
                        DatabaseManagerUtils.initStatement(stmt);
                        Display.getDefault().asyncExec(new Runnable() {

                            public void run() {
                                sqlEditorComposite.getDialog().getContentComposite().getDataBrowserComposite()
                                        .updateDefaultTable(DatabaseManagerUtils.getColumnNames(),
                                                DatabaseManagerUtils.getDataSetRowList());
                            }
                        });
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    } catch (CoreException ex) {
                        ex.printStackTrace();
                    } catch (ClassNotFoundException ex) {
                        ex.printStackTrace();
                    } finally {
                        monitor.done();
                    }
                } else if (id == AbstractEditorComposite.DATA) {
                    try {
                        final Connection conn = CorePlugin.getDefault().getDesignerCoreService().getCurrentConnection();
                        conn.commit();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } catch (CoreException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }

                }

            }
        };
        DatabaseManagerDialog dialog = sqlEditorComposite.getDialog();
        UIUtils.runWithProgress(progress, true, dialog.getProgressMonitor(), dialog.getShell());
    }
}
